/*
* 所有游戏逻辑有关的代码
* 方法：开始游戏start();
* 属性：蛇，食物，地图
* */
(function (window) {
    var that = null;
    function Game(map) {
        this.food = new Food();//食物是创建出来的
        this.snake = new Snake();//蛇是创建出来的
        this.map = map;//地图是传进来的
        that = this;
    }
    //游戏开始的方法
    //在地图上渲染出蛇和食物
    Game.prototype.start = function () {
        this.food.render(this.map);
        this.snake.render(this.map);

        // this.snake.move();
        // this.snake.render(this.map);
        snakeAutoMove ();
        bindkey();
    };


    function snakeAutoMove () {
        var timerid = setInterval(function () {
            this.snake.move(this.food);
            this.snake.render(this.map);


            //判断蛇头有没有撞墙

            var snakeHeadX = this.snake.body[0].x*this.snake.width;
            var snakeHeadY = this.snake.body[0].y*this.snake.height;
            console.log(snakeHeadX);
            if (snakeHeadX >= map.offsetWidth || snakeHeadX < -1 || snakeHeadY < -1 || snakeHeadY >= map.offsetHeight) {

                clearInterval(timerid);
                alert('Game Over');

            }

            //上下文调用模式.bind()
        }.bind(that),300)

    }

    //让蛇根据按键移动
    function bindkey() {
        window.onkeydown = function (e) {
            e = e || window.event;
            switch (e.keyCode) {
                //不能反向按键移动
                case 37:
                    if (this.snake.direction != 'right') {
                        this.snake.direction = 'left';
                    }
                    break;
                case 38:
                    if (this.snake.direction != 'bottom') {
                        this.snake.direction = 'top';
                    }
                    break;
                case 39:
                    if (this.snake.direction != 'left') {
                        this.snake.direction = 'right';
                    }
                    break;
                case 40:
                    if (this.snake.direction != 'top') {
                        this.snake.direction = 'bottom';
                    }
                    break;
            }

        }.bind(that);
    }


    //暴露出接口
    window.Game = Game;
}(window));